<template>
	<view class="content">
		<view class="top-box">
			<input class="item" v-model="dataAll.text" type="text" placeholder="名称" />
			<input class="item" v-model="dataAll.path" type="text" placeholder="地址" />
		</view>
		<view class="btn" @click="save()">
			保存
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		reactive,
		ref
	} from 'vue'

	const oldJson = ref([]) // 用来存储已加载的本地数据
	const id = ref(0)
	const dataAll = reactive({
		text: '',
		path: '',
		id: '',
		index: ''
	})

	// 保存数据
	const save = () => {
		let data = []

		for (var i = 0; i < oldJson.value.length; i++) {
			if (i == dataAll.id) {
				let json = {
					text: dataAll.text,
					path: dataAll.path,
					index: dataAll.index
				}
				data.push(json)
			}
			if (i != dataAll.id) {
				let json = oldJson.value[i]
				data.push(json)
			}
		}
		
		console.log(data);
		
		uni.setStorage({
			key: "data",
			data: JSON.stringify(data),
			success: () => {
				uni.showToast({
					title: '保存成功',
					icon: 'success'
				})
			}
		})
	}

	onLoad((resdata) => {
		console.log(resdata);
		id.value = resdata.id
		dataAll.id = resdata.id
		uni.getStorage({
			key: "data",
			success(res) {
				let data = JSON.parse(res.data)
				oldJson.value = data
				dataAll.index = data[resdata.id].index
				dataAll.path = data[resdata.id].path
				dataAll.text = data[resdata.id].text
			},
			fail(err) {
				oldJson.value = []
			}
		})
	})
</script>

<style lang="scss" scoped>
	.content {
		padding: 0 20rpx;
		height: 100vh;

		.top-box {
			padding-top: 40rpx;

			.item {
				border-bottom: 1px solid gainsboro;
				padding: 20rpx 20rpx;
				font-size: 30rpx;
			}
		}

		.btn {
			margin-top: 40rpx;
			line-height: 100rpx;
			color: white;
			background-color: #005BAB;
			text-align: center;
			border-radius: 20rpx;
		}
	}
</style>